import os
import sys
import json

import yaml
import logging

from exception.FunCallError import FunCallError
from utils.dict_utils import get_dict_value

config_log=logging.getLogger("config")

class AIConfigHandler():


    def __init__(self, fileName="app.yaml"):
        self.java_map = {}
        #如果文件名本身已指定目录,则直接使用,否则使用安装目录作为默认路径
        if "\\" in fileName or "/" in fileName:
            self.fileName = fileName
        else:
            # 使用 pyinstaller 打包后,路径不对,使用该方式获取可用的配置文件目录 start
            if getattr(sys, 'frozen', False):
                absPath = os.path.dirname(os.path.abspath(sys.executable))
            elif __file__:
                absPath = os.path.dirname(os.path.abspath(__file__))
            _tmp = os.sep + "conf"
            if absPath.endswith(_tmp) :
                absPath=absPath[:-len(_tmp)]
            self.absPath = absPath

            # 使用 pyinstaller 打包后,路径不对,使用该方式获取可用的配置文件目录 end
            config_log.debug("absPath=" + absPath)
            self.fileName = absPath + os.sep + fileName

    def read_conf(self, encoding='utf-8'):
        """读取yaml数据"""
        with open(self.fileName, encoding=encoding) as f:
            # tmp=yaml.load(f.read(), Loader=yaml.FullLoader)
            tmp = yaml.safe_load(f.read())
            if 'profiles' in tmp['ai']:
                if 'active' in tmp['ai']['profiles']:
                    for ac in tmp['ai']['profiles']['active'].split(','):
                        ac=ac.strip()
                        fileNameTmp = self.absPath + os.sep +"app-"+ ac+".yaml"
                        file_tmp=open(fileNameTmp, encoding=encoding)
                        dict_tmp = yaml.safe_load(file_tmp.read())
                        from deepmerge import always_merger
                        tmp = always_merger.merge(tmp, dict_tmp)

            global AppConf
            AppConf=tmp
            jdk_list = get_jdk_list()
            for j in jdk_list:
                self.java_map = {j['version']: j['java_home']}

            return tmp


    # def write_yaml(self, data, encoding='utf-8'):
    #     """向yaml文件写入数据"""
    #     with open(self.file, encoding=encoding, mode='w') as f:
    #         return yaml.dump(data, stream=f, allow_unicode=True)

def get_environ():
    _env = dict(os.environ)  # 复制当前环境变量
    env_tmp=get_dict_value(AppConf, 'ai.funcall.environ')
    if env_tmp is None:
        return _env
    for k, v in env_tmp.items():
        # print(f"---------------\t{k}={v}")
        _env[k] = v
    return _env

def get_jdk_list():
    global AppConf
    jdk_list = get_dict_value(AppConf, 'ai.funcall.jdk')
    return jdk_list if jdk_list is not None else []

def get_jdk_version_list(self):
    java_version=[]
    jdk_list = self.get_jdk_list()
    for j in jdk_list:
        java_version.append(j['version'])

    return java_version

def get_jdk_home(self,jdk_version):
    if jdk_version not in self.java_map:
        raise FunCallError("指定jdk版本号不存在")
    return self.java_map[jdk_version]

#设置 jdk 环境变量,返回可在终端运行的java命令(类似mvn.cmd中的 JAVA_CMD)
def set_jdk_to_env(self,env,jdk_home):
    env['JAVA_HOME'] = jdk_home  # 修改或添加环境变量
    import platform
    if platform.system() == 'Windows':
        # print("当前操作系统是Windows")
        env['CLASSPATH'] = "%JAVA_HOME%/lib/tools.jar;%JAVA_HOME%/lib/dt.jar;."
        java_cmd = jdk_home + '\\bin\\java.exe'
        javac_cmd = jdk_home + '\\bin\\javac.exe'
        env['PATH']=f"%JAVA_HOME%\\bin;%PATH%"
    else:
        # print("当前操作系统不是Windows")
        env['CLASSPATH'] = "$JAVA_HOME/lib/tools.jar:$JAVA_HOME/lib/dt.jar:."
        java_cmd = jdk_home + '/bin/java'
        javac_cmd = jdk_home + '/bin/javac'
        env['PATH'] = f"$JAVA_HOME/bin:$PATH"
    return {
        "JAVA_CMD": java_cmd,
        "JAVAC_CMD": javac_cmd,
    }

AppConf = AIConfigHandler().read_conf()

if __name__ == '__main__':
    # 设置 logging 级别为 DEBUG
    logging.basicConfig(level=logging.DEBUG)
    # appConf=AIConfigHandler().read_conf()
    print(json.dumps(AppConf))
    print(AppConf['ai'])
